package com.summer.utils.apktool;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.Iterator;
import java.util.List;

public class Dom4jUtils {

    public static void main(String[] args) {

        String mainFestXml = getNameAttrByAndroidManifestXml("/Users/haoyitao/Documents/需求/old/apk下载/yaml-xml parse/AndroidManifest.xml");
        String name = mainFestXml.split("/")[1];
        System.out.println(mainFestXml);
        System.out.println(name);
        //先根据AndroidManifest.xml 获取 应用名标识
        //在根据标识 从 strings.xml 获取应用名
    }

    // TODO
    public static String getApplicationNameByStringXml(String apkPath, String label){
        // 解析books.xml文件
        // 创建SAXReader的对象reader
        SAXReader reader = new SAXReader();
        try {
            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
            //Document document = reader.read(new File("/Users/haoyitao/Documents/需求/apk下载/yaml-xml parse/AndroidManifest.xml"));
            Document document = reader.read(new File(apkPath+"/res/values/strings.xml"));
            Node node = document.selectSingleNode("/resources/string[@name='"+label+"']");
            return node.getText();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    public static String getApplicationName(String apkPath){
        // 解析books.xml文件
        // 创建SAXReader的对象reader
        String lable = getNameAttrByAndroidManifestXml(apkPath);
        if(StringUtils.isEmpty(lable)){
            throw new RuntimeException("获取文本内容不能为空！");
        }
        String name = lable.split("/")[1];

        return getApplicationNameByStringXml(apkPath,name);
    }

    public static String getNameAttrByAndroidManifestXml(String apkPath){
        // 解析books.xml文件
        // 创建SAXReader的对象reader
        SAXReader reader = new SAXReader();
        try {
            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
            //Document document = reader.read(new File("/Users/haoyitao/Documents/需求/apk下载/yaml-xml parse/AndroidManifest.xml"));
            Document document = reader.read(new File(apkPath+"/AndroidManifest.xml"));
            List list = document.selectNodes("/manifest/application/@android:label");
            for (Iterator it = list.iterator(); it.hasNext();) {
                Attribute attr = (Attribute) it.next();
                return attr.getValue();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


}
